<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="问题名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入问题名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['system:question:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="题目类型" align="center" prop="type" />-->
      <el-table-column label="问题名称" align="center" prop="title" />
<!--      <el-table-column label="正确答案" align="center" prop="correctOption" />-->
      <el-table-column align="center" label="问题解析" prop="analysis" />
      <el-table-column label="问题分数" align="center" prop="score" />
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试题对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="问题名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入问题名称" />
        </el-form-item>
        <!--        题目类型-->
        <el-form-item label="题目类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择题目类型" @change="selectchange">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <!--        选项-->
        <el-form-item label="选项" prop="option">
          <div v-if="form.type == 0">
            <div v-for="(jud,indexjud) in form.options" :key="indexjud">
              <span>{{jud.option}}</span>
              <el-input
                v-model="jud.content"
                type="text"
                placeholder="请输入内容"
                class="addoption"
                readonly
              />
            </div>
          </div>
          <div v-else-if="form.type == 1">
            <div v-for="(opt,indexopt) in form.options" :key="indexopt">
              <span>{{opt.option}}</span>
              <el-input
                required
                v-model="opt.content"
                type="text"
                placeholder="请输入内容"
                class="addoption"
              />
<!--              <i class="el-icon-delete" @click="deloption(indexopt)"></i>-->
            </div>
          </div>
          <div v-else>
            <div v-for="(check,indexcheck) in form.options" :key="indexcheck">
              <span>{{check.option}}</span>
              <el-input v-model="check.content" type="text" placeholder="请输入内容" class="addoption" />
              <i class="el-icon-delete" @click="delcheckion(indexcheck)"></i>
            </div>
          </div>
        </el-form-item>
        <!--        正确答案-->
        <el-form-item label="正确答案" prop="correctOption">
          <el-input type="text" placeholder="请先选择题目类型" v-show="!form.type" disabled />
          <el-radio-group v-model="form.correctOption" @change="radiochange" v-show="form.type == 1">
            <el-radio
              v-for="(item) in form.options"
              :label="item.optionId"
            >{{item.option}}</el-radio>
          </el-radio-group>
          <el-radio-group v-model="radio" @change="judgechange" v-show="form.type == 0">
            <el-radio :label="0">A</el-radio>
            <el-radio :label="1">B</el-radio>
          </el-radio-group>
          <el-checkbox-group
            v-model="checkList"
            v-show="form.type == 2"
            @change="checkboxchange"
          >
            <el-checkbox
              v-for="(item) in form.options"
              :label="item.optionId"
            >{{item.option}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="问题解析" prop="analysis">
          <el-input placeholder="请输入问题解析" type="textarea" v-model="form.analysis" />
        </el-form-item>
        <el-form-item label="问题分数" prop="score">
          <el-input v-model="form.score" placeholder="请输入问题分数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion, exportQuestion } from "@/api/system/question";

  export default {
    name: "Question",
    data() {
      return {
        isAdd:true,
        // 正确答案
        menu: ["A", "B", "C", "D"],
        radio: "",
        letterlist: [1, 2, 3, 4],
        checkboxlist: [1, 2, 3, 4],
        checkList: [],

        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 试题表格数据
        questionList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          title: undefined,
          correctOption: '',
          analysis: undefined,
          score: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        },
        //试题类型
        options: [
          {
            value: "1",
            label: "单选",
          },
          {
            value: "2",
            label: "多选",
          },
        ],
      };
    },
    created() {
      this.getList();
    },
    methods: {
      // 正确答案
      radiochange(e) {
        console.log('radio 单选',e,this.form.options);
        if(this.isAdd){
          console.log('正确答案',this.form.options[e].optionId)
          // 编辑
          this.form.correctOption=this.form.options[e].optionId
          // 新增
          this.form.options.forEach((r) => {
            this.form.options[e].correct = 1
          })
        } else {
          // 编辑
          this.form.correctOption = e
        }

      },
      judgechange(e) {
        this.judgelist[e].correct = 1;
      },
      checkboxchange(e) {
        console.log(e, this.isAdd ? '新增' : '编辑',this.form)
        if(this.isAdd){
          this.form.correctOption=""
          e.forEach((i) => {
            this.form.correctOption += this.form.options[i].optionId+","
            this.form.options[i].correct = 1
          });
        } else {
          this.checkList= e
          console.log('checkbox 多选', this.checkList,this.form.correctOption)
        }
      },

      // 题目类型
      selectchange(e) {
        // console.log('切换下拉框',e, this.form.type, this.form)
        this.form.options=[
          {"option": "A","content":"", correct: 0 ,optionId:0},
          {"option": "B","content":"", correct: 0 ,optionId:1},
          {"option": "C","content":"", correct: 0 ,optionId:2},
          {"option": "D","content":"", correct: 0 ,optionId:3}
        ]
      },
      /** 查询试题列表 */
      getList() {
        this.loading = true;
        listQuestion(this.queryParams).then(response => {
          this.questionList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.checkList= []
        this.form = {
          questionId: undefined,
          title: undefined,
          correctOption: -1,
          analysis: undefined,
          score: undefined,
          options:[
            {"option": "A","content":"", correct: 0 ,optionId:0},
            {"option": "B","content":"", correct: 0 ,optionId:1},
            {"option": "C","content":"", correct: 0 ,optionId:2},
            {"option": "D","content":"", correct: 0 ,optionId:3}
          ],
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.questionId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.isAdd = true;
        this.open = true;
        this.title = "添加试题";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.isAdd = false
        const questionId = row.questionId || this.ids
        getQuestion(questionId).then(response => {
          console.log('edit', response.data)
          this.form = response.data;
          if(this.form.type === "1"){
            this.form.correctOption = parseInt(this.form.correctOption)
          }else {
            this.checkList = this.form.correctOption.split(',')
            this.checkList = this.checkList.map(i => {
              i = parseInt(i)
              return i
            })
          }
          console.log('checkList', this.checkList)
          this.open = true;
          this.title = "修改试题";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            // 添加选项
            if (this.form.questionId != undefined) {
              /*if(this.form.correctOption.length > 1){
                this.form.correctOption = this.form.correctOption.substr(0,this.form.correctOption.length-1)
              }*/
              if(this.form.type === '2'){
                this.form.correctOption = this.checkList.join(',')
              }
              console.log('修改提交', this.form)
              // return
              updateQuestion(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              console.log('新增提交', this.form)
              // return
              addQuestion(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const questionIds = row.questionId || this.ids;
        this.$confirm('是否确认删除试题编号为"' + questionIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delQuestion(questionIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有试题数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportQuestion(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
      }
    }
  };
</script>

<style scoped>
  .addoption {
    margin: 5px;
    width: 88%;
  }
</style>
